#!/bin/sh
#
#  Stops and starts the peer service
#

#PEER_HOME=
PROG="ourgrid-peer"

# Check that we are root ... so non-root users stop here
[ "`id -u`" = 0 ] || exit 1

# If pid file path is not set in sysconfig, set to /var/run/prog.pid.
[ -z "$PEER_PIDFILE" ] && PEER_PIDFILE=/var/run/$PROG.pid

PEER_CMD="java -cp $PEER_HOME/lib/ourgrid.jar:$PEER_HOME/lib/commune.jar:$PEER_HOME/lib/log4j.jar:$PEER_HOME/lib/nodewiz.jar:$PEER_HOME/lib/smack.jar:$PEER_HOME/lib/smackx.jar:$PEER_HOME/lib/smackx.jar:$PEER_HOME/lib/commons-codec-1.3.jar:$PEER_HOME/lib/commons-io-1.3.2.jar:$PEER_HOME/lib/commons-math-1.1.jar org.ourgrid.peer.ui.sync.Main"

start() {
	OLD_PWD=`pwd`
	cd $PEER_HOME

    # Start daemons.
    echo -n "Starting $PROG: "

	"$PEER_CMD" start > nohup.out 2>&1 &
	RETVAL=$?

	if [ $RETVAL -eq 0 -a ! -z "$PEER_PIDFILE" ]; then
		echo $! > $PEER_PIDFILE
	fi

	echo

	[ $RETVAL -eq 0 -a -d /var/lock/subsys ] && touch /var/lock/subsys/$PROG

	sleep 1 # allows prompt to return
	cd $OLD_PWD
}

stop() {
	# Stop daemons.
	echo -n "Shutting down $PROG: "

	OLD_PWD=`pwd`
	cd $PEER_HOME

    # Start daemons.
    echo -n "Starting $PROG: "

	"$PEER_CMD" stop > nohup.out 2>&1 &
	RETVAL=$?
	echo

	[ $RETVAL -eq 0 -a -f "$PEER_PIDFILE" ] && rm -f $PEER_PIDFILE
	[ $RETVAL -eq 0 -a -f "/var/lock/subsys/$PROG" ] && rm -f /var/lock/subsys/$PROG
	
	sleep 1 # allows prompt to return
	cd $OLD_PWD
}

restart() {
	stop
	sleep 10 # give it a few moments to shut down
	start
}

appstatus() {
	echo -n "$PROG status: "

	OLD_PWD=`pwd`
	cd $PEER_HOME

	"$PEER_CMD" status > nohup.out 2>&1 &
	echo

	cd $OLD_PWD
}

status() {
	pid=`cat $PEER_PIDFILE 2>&1`
	if [ "$?" = "1" ]; then
		echo "OurGrid Peer is not running"
		RETVAL=0
	else 
		ps -p $pid > /dev/null 2>&1
		if [ "$?" = "0" ]; then 
			echo "OurGrid Peer is running"
			appstatus
			RETVAL=0
		else 
			echo "OurGrid Peer is not running"
			RETVAL=0
		fi
	fi
}

# Handle how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	status) 
		status
		;;
	*)
		echo "Usage $0 {start|stop|restart|status}"
		RETVAL=1
esac

exit $RETVAL
